﻿using HLStock.Common;
using HLStock.Model;
using HLStock.MyExcep;
using HLStock.WmsApi.AuthenticationInjection;
using HLStock.WmsApi;
using HLStock.WmsService;
using Microsoft.AspNetCore.Mvc;

namespace HLStock.Controllers
{
    public class UserController : MyBaseController<UserModel>
    {
        UserServiceProvider userSP;
        public UserController() : base()
        {
            userSP = (UserServiceProvider)getSp();
        }
        protected override BaseServiceProvider<UserModel> getSp()
        {
            return ServiceLoader.GetService<UserServiceProvider>();
        }
        [HttpPost]
        public ResponseData<OnlineUser> Login(dynamic data)
        {
            var user = (string)data.user;
            var pwd = (string)data.password;
            var usermodel = userSP.VerifyPassword(user, pwd);
            if (usermodel == null) throw new MyAuthorizationException($"用户{user}身份验证失败");
            var onlineUser = userSP.MakeOnLineUser(usermodel.Pk);
            ResponseData<OnlineUser> result = new ResponseData<OnlineUser>(onlineUser);
            return result;
        }
        [HttpPost, MyAuthorize(AuthorizeLevelEnum.AllUser)]
        public ResponseData<string> ResetPassword()
        {
            //获取当前登录的usercode
            var onlineUser = ServiceLoader.GetService<OnlineUser>();
            var password = userSP.ResetPassword(onlineUser.UserCode);
            ResponseData<string> result = new ResponseData<string>(password);
            return result;
        }
        [HttpPost, MyAuthorize(AuthorizeLevelEnum.AllUser)]
        public ResponseData<OnlineUser> WhoAmI()
        {
            var onlineUser = ServiceLoader.GetService<OnlineUser>();
            return new ResponseData<OnlineUser>(onlineUser); 
        }
    }
}
